package com.svms.indent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Button;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.svms.service.vo.IndentVO;
import com.svms.service.vo.VehicleSpareVO;
import com.svms.utils.SvmsMessageUtils;
import com.svms.web.constants.SvmsResources;
import com.svms.web.factory.SvmsWebFactory;

/**
 * @author om39a
 * 
 */
public class ManageIndentCtrl extends GenericForwardComposer<Window> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Window window_manage_indent;

	private Textbox txb_page_size;
	private Button btn_indent_help;
	private Button btn_indent_refresh;
	private Button btn_search_indent_list;
	private Button btn_add_indent;
	private Button btn_edit_indent;

	private Listbox lstbx_indents;
	private ListModelList<IndentVO> lst_model_indent;

	public Listbox getLstbx_indents() {
		return lstbx_indents;
	}

	public void setLstbx_indents(Listbox lstbx_indents) {
		this.lstbx_indents = lstbx_indents;
	}

	@Override
	public ComponentInfo doBeforeCompose(Page page, Component parent,
			ComponentInfo compInfo) {

		System.out.println("Spare doBeforeCompose ");
		loadSpareCodeToListModal();

		return super.doBeforeCompose(page, parent, compInfo);
	}

	@Override
	public void doAfterCompose(Window comp) throws Exception {
		System.out.println("Spare doAfterCompose ");
		super.doAfterCompose(comp);
	}

	private void loadSpareCodeToListModal() {
		List<IndentVO> indents = SvmsWebFactory.indentService().getIndentList();
		System.out.println("ooo");
		System.out.println(indents);
		System.out.println("ooo");
		lst_model_indent = new ListModelList<IndentVO>(indents);

	}

	/**
	 * Populates the Indent Details list
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void onCreate$window_manage_indent(Event event) throws Exception {
		System.out.println("Spare onCreate$window_manage_indent");
		setSpareCodeListModalToListBox();
		setPageSize();
	}

	/**
	 * To set the paging size for the list
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void onBlur$txb_page_size(Event event) throws Exception {
		setPageSize();
	}

	private void setSpareCodeListModalToListBox() {
		lstbx_indents.setModel(lst_model_indent);
		lstbx_indents.setMold("paging");
		lstbx_indents.setItemRenderer(new ListitemRenderer<IndentVO>() {

			@Override
			public void render(Listitem item, IndentVO data, int index)
					throws Exception {

				final IndentVO indent = data;

				Listcell lc = new Listcell(indent.getIndentId());
				lc.setParent(item);
				lc = new Listcell(indent.getInvoiceNumber());
				lc.setParent(item);
				lc = new Listcell(formatDate(indent.getInvoiceDate()));
				lc.setParent(item);

				// Extracting Vehicle ID's and Transport IDs

				List<VehicleSpareVO> billItems = indent.getBillItems();
				StringBuffer vehicleNumbers = new StringBuffer();
				StringBuffer transportIDs = new StringBuffer();

				if (billItems != null) {
					for (VehicleSpareVO vehicleSpareVO : billItems) {
						if (vehicleSpareVO.getVehicleVO() != null) {
							vehicleNumbers.append(vehicleSpareVO.getVehicleVO()
									.getVehicleNumber());
							vehicleNumbers.append(", ");
							transportIDs.append(vehicleSpareVO.getVehicleVO()
									.getTransport().getCompanyName());
							transportIDs.append(", ");
						}
					}
				}

				lc = new Listcell(vehicleNumbers.toString());
				lc.setParent(item);
				lc = new Listcell(transportIDs.toString());
				lc.setParent(item);
				lc = new Listcell(indent.getAmount());
				lc.setParent(item);
				lc = new Listcell(indent.isApproved() ? "Approved"
						: "Not Approved");
				lc.setParent(item);

				item.setAttribute("selectedIndentDetail", data);

				ComponentsCtrl.applyForward(item,
						"onDoubleClick=onIndentItemDoubleClicked");

			}

			private String formatDate(Date date) {
				String formatedDate = null;
				if (date != null) {
					SimpleDateFormat dateFormat = new SimpleDateFormat(
							"dd-MMM-yyyy");
					formatedDate = dateFormat.format(date);
				}
				return formatedDate;
			}
		});

		btn_edit_indent.setDisabled(false);
		btn_add_indent.setDisabled(false);
		btn_indent_help.setDisabled(false);
		btn_indent_refresh.setDisabled(false);
		btn_search_indent_list.setDisabled(false);

		txb_page_size.setDisabled(false);
		txb_page_size.setValue(null);
		txb_page_size.setMaxlength(2);
	}

	private void setPageSize() {
		if (StringUtils.isNotBlank(txb_page_size.getValue())) {
			try {
				lstbx_indents.setPageSize(Integer.valueOf(txb_page_size
						.getValue()));
			} catch (Exception e) {
				SvmsMessageUtils
						.showErrorMessage("Page size can only be a number");
			}
		} else {
			lstbx_indents.setPageSize(8);
		}
	}

	/**
	 * To reset the indent list to current values in database
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void onClick$btn_indent_refresh(Event event) throws Exception {
		loadSpareCodeToListModal();
		setSpareCodeListModalToListBox();
	}

	/**
	 * To make a add vehicle call
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void onClick$btn_add_indent(Event event) throws Exception {
		showDetailView(null);
	}

	public void onClick$btn_edit_indent(Event event) throws Exception {
		loadEditWindow();
	}

	/**
	 * To display help menu
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void onClick$btn_indent_help(Event event) throws Exception {
		StringBuffer helpMessage = new StringBuffer();
		helpMessage
				.append("---------------------------------------------------------");
		helpMessage.append("\n");
		helpMessage.append("1. Add Indent button to add a new vehicle");
		helpMessage.append("\n");
		helpMessage.append("2. Search to find a indent in system");
		helpMessage.append("\n");
		helpMessage.append("3. Refresh to get a latest update from system");
		helpMessage.append("\n");
		helpMessage.append("4. Double click on the vehicle in list to edit it");
		helpMessage.append("\n");
		helpMessage
				.append("---------------------------------------------------------");
		SvmsMessageUtils.showGenericMessage(helpMessage.toString());
	}

	/**
	 * To search for vehicles from the main vehicle window
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void onClick$btn_search_indent_list(Event event) throws Exception {
		Map<String, Object> args = new HashMap<String, Object>();
		args.put("manageIndentCtrl", this);
		Window win = null;
		try {
			win = (Window) Executions.createComponents(
					SvmsResources.INDENT_SEARCH_DIALOGUE, null, args);
		} catch (final Exception e) {
			e.printStackTrace();
			SvmsMessageUtils.showErrorMessage(e.getMessage());
			if (win != null) {
				win.detach();
			}
		}
	}

	/**
	 * To perform the double click event on the list items
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void onIndentItemDoubleClicked(Event event) throws Exception {

		loadEditWindow();

	}

	private void loadEditWindow() throws Exception {
		Listitem item = this.lstbx_indents.getSelectedItem();

		if (item != null) {
			IndentVO indentVO = (IndentVO) item
					.getAttribute("selectedIndentDetail");
			System.out.println("...............");
			System.out.println(indentVO);
			System.out.println("...............");
			showDetailView(indentVO);
		} else {
			SvmsMessageUtils
					.showErrorMessage("Select a item from list to edit");
		}
	}

	/**
	 * Opens the detail view of the Vehicle Controller. <br>
	 * Overhanded some params in a map if needed. <br>
	 * 
	 * @param branche
	 * @throws Exception
	 */
	private void showDetailView(IndentVO indent) throws Exception {

		final HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("selectedIndentDetail", indent);
		map.put("manageIndentCtrl", this);
		Window win = null;
		try {
			win = (Window) Executions.createComponents(
					SvmsResources.MANAGE_INDENT_DIALOGUE, null, map);
		} catch (final Exception e) {
			e.printStackTrace();
			SvmsMessageUtils.showErrorMessage(e.getMessage());
			if (win != null) {
				win.detach();
			}
		}
	}

}
